package com.wonderful.eyepetizer.ui.pages.discover

import android.util.Log
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.viewModelScope
import androidx.paging.cachedIn
import com.wonderful.eyepetizer.app.base.BaseViewModel
import com.wonderful.eyepetizer.data.entity.bean.Category
import com.wonderful.eyepetizer.data.repo.MainRepo
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * Desc:
 * @Author: wonderful
 * @Time: 2024/2/21 14:11
 */
@HiltViewModel
class DiscoverViewModel @Inject constructor(private val mRepo: MainRepo) : BaseViewModel() {
    var tabIndex = mutableIntStateOf(0)

    var followRefreshing = mutableStateOf(false)
    var categoryRefreshing = mutableStateOf(false)
    var topicRefreshing = mutableStateOf(false)
    var newsRefreshing = mutableStateOf(false)
    var recommendRefreshing = mutableStateOf(false)

    val categoryList = mutableStateListOf<Category>()

    val followPageFlow = mRepo.getFollowList(followRefreshing).cachedIn(viewModelScope)

    fun getCategoryList() {
        viewModelScope.launch {
            categoryRefreshing.value = true
            mRepo.getCategoryList().data?.let { items ->
                if (items.isNotEmpty()) {
                    categoryList.clear()
                    categoryList.addAll(items)
                }
            }
            categoryRefreshing.value = false
        }
    }

    val topicPageFlow = mRepo.getTopicList(topicRefreshing).cachedIn(viewModelScope)

    val newsPageFlow = mRepo.getNewsList(newsRefreshing).cachedIn(viewModelScope)

    val recommendFlow = mRepo.getRecommendList(recommendRefreshing).cachedIn(viewModelScope)

    // 测试一次顺序请求多个接口
    fun testRequestMultiApi() {
        viewModelScope.launch {
            val defer1 = async { mRepo.getCategoryList() }
            val defer2 = async { mRepo.getCategoryList() }
            val res1 = defer1.await()
            val res2 = defer2.await()
            Log.e("testRequestMultiApi", "res1=$res1 res2=$res2")
        }

    }

    init {
        getCategoryList()
    }
}